#!/usr/bin/env python

# -*- coding: utf-8 -*

"""
超声波传感器，用于测距
"""

from py_code.driver.Pin import Pin
from py_code.SingletonType import SingletonType
from py_code.driver.GpioDriver import GpioDriver
import RPi.GPIO as GPIO
import logging
import time


class Ultrasonic(GpioDriver, metaclass = SingletonType):
    """超声波 用于测距"""
    pins = [Pin(18, GPIO.IN, description = "echo"), Pin(16, GPIO.OUT, description = "trig")]
    
    def distance(self) -> float:
        """
        测距
        @return 距离，单位应该是cm
        """

        # 首先发出一声超声波 所以是发出低高低信号
        self.pins[1].writeLow()
        time.sleep(0.000002)
        self.pins[1].writeHigh()
        time.sleep(0.000005)
        self.pins[1].writeLow()

        timeout = 0.3
        # 等待接收到超声波
        logging.debug(f"超声波开始测距")
        t3 = time.time()
        while not self.pins[0].read(noLog=True):
            t4 = time.time()
            if (t4 - t3) > timeout:
                logging.warning(f"等待超声波超时：超过{timeout}s")
                return -1
        # 等待超声波接收完成
        t1 = time.time()
        while self.pins[0].read(noLog=True):
            t5 = time.time()
            if (t5 - t1) > timeout:
                logging.warning(f"超声波持续接收超时：超过{timeout}s")
                return -1

        t2 = time.time()
        v = ((t2 - t1) * 340 / 2) * 100
        logging.basicConfig(level=logging.DEBUG)
        logging.debug(f"超声波测距完成，距离：{v}，用时：{t2 - t3}s")
        return v
  